package TuringMachine;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Parser {
	public boolean readFile(File archivo, TuringMachine tm) throws IOException{
		boolean error=false;
        BufferedReader machine= new BufferedReader(new FileReader(archivo));
        String linea="";
        do {
            linea = machine.readLine();
            error=lineParser(linea, tm);
        } while((linea != null) &&(!error)); 
        return error;
	}
	
	static final boolean lineParser(String linea, TuringMachine tm){
		String currentState, nextState, action;
		Integer position;
		if(linea==null){
			return false;
		}
		String aux[] =linea.split(",");
		if(aux.length != 4 ){
			System.err.println("El formato del archivo es invalido!");
			System.exit(2);
		}
		currentState=aux[0];
		position =Integer.parseInt(aux[1]);		
		nextState=aux[2];
		action=aux[3];
		
		if(!validState(currentState) || !validState(nextState) || !validateAction(action)){
			System.err.println("El formato del archivo es invalido!");
			System.exit(2);
		}

		Map<Integer, Movement> node = new HashMap<Integer, Movement>();
		node.put(position, new Movement(action, nextState));
		return !tm.addNode(currentState, node);
	}

	private static boolean validateAction(String action) {
		Pattern p = Pattern.compile("[0-2><]");
	    Matcher m = p.matcher(action);
	    return m.matches();
	}

	private static boolean validState(String state) {
		 Pattern p = Pattern.compile("[A-Za-z0-9]+");
	     Matcher m = p.matcher(state);
	     return m.matches();
	}

	public Map<Integer, Integer> createTape() {
		Map<Integer, Integer> tape = new HashMap<Integer, Integer>();
		int aux, i=0;
		char c;
		try {
			while( (aux= System.in.read() )!= -1){
				c=(char)aux;
				if((c!='0') && (c!='1') && (c!='2')){
					System.err.println("\nLa cadena ingresada es incorrecta!");
					System.exit(1);
				}
				tape.put(i++, Integer.parseInt(String.valueOf(c)));
			}
		} catch (IOException e) {
			System.out.println("ERROR");
		}
		System.out.println("");
		return tape;
	}


}
